from flask import Blueprint,request,jsonify
import json
from database import *
from conf.comm import sqlalchemy_context

bp_cates = Blueprint('cates', __name__)



# 
def xtree(data):
    if data:
        tree = {}
        list = []
        # 根据id解析程字典
        for i in data:
            # id 作为key    i作为值
            tree[i['id']] = i
        for j in data:
            # 判断父id是否等于0  等于0则直接添加到列表里
            if j['parent'] ==0:
                list.append(j)
            else:
                # 如果son不在tree 字典里  则自己定义空字典  如果在 则直接添加
                if 'son' not in tree[j['parent']]:
                    tree[j['parent']]['son'] = []
                tree[j['parent']]['son'].append(j)
        return list
    else:
        return data
@bp_cates.route('/addclass/',methods=['POST','GET'])
@sqlalchemy_context()
# 添加分类接口
def addclass():
    if request.method =='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        
        # parent = ''
        # try:
        #     parent = data['parent']
        # except :
        #     parent = ''
        try:
            cate = Cate(name=data['name'],level=data['level'],params=data['params'],parent=data['parent'])
            db.session.add(cate)
            db.session.commit()
            return jsonify({'code':200,'mes':'添加成功'})
        except:
            return jsonify({'code':10031,'mes':'添加失败'})
    elif request.method == 'GET':
        # 获取所有数据
        cate = Cate.query.all()
        if cate:  # 如果存在遍历他
            list = []
            for i in cate:
                list.append({'id':i.id,'name':i.name,'level':i.level,'parent':i.parent,'params':i.params})
            list = xtree(list)
            return jsonify({'code':200,'list':list})
        else:
            return jsonify({'code':10032,'list':list})
    
import os
import uuid
# 课程上传
@bp_cates.route('/CateMarage/',methods=['POST','GET'])
@sqlalchemy_context()
def CateMarage():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.format()
        # print(uuidpic)
        cate = Course(name=data['name'],description=data['description'],tname=data['tname'],pic=data['pic'],vedios=data['vedios'],cid=data['cid'])
        db.session.add(cate)
        try:
            db.session.commit()
            return jsonify({"code":200,'msg':'上传成功'})
        except:
            return jsonify({"code":403,'msg':'上传失败'})
        
    elif request.method=='GET':
        # 获取id
        id = request.args.get('id')
        if id:
            course = Course.query.filter_by(id=id).first()
            onelist = {'id':course.id,'name':course.name,'description':course.description,'tname':course.tname,'pic':course.pic,'vedios':course.vedios,'cid':course.cid}
            print(onelist)
            return jsonify({"code":200,'onelist':onelist})
        # 当前页
        page =int(request.args.get('page'))
        #每页多少条
        size = int(request.args.get('size'))
        # 读取数据
        start = (page-1)*size
        course = Course.query.offset(start).limit(size)
        # 对结果进行解析
        list = []
        if course:
            for i in course:
                list.append({'id':i.id,'name':i.name,'pic':i.pic,"tname":i.tname,'description':i.description})
        # 共有多少条记录
        total = Course.query.count()
        return jsonify({"code":200,'list':list,'total':total})


# 视频 接口
@bp_cates.route('/uploda/',methods=['POST'])
@sqlalchemy_context()
def uploda():
    if request.method == 'POST':
        
        # 获取文件
        file = request.files['file']
        userid = request.form.get("userid")
        
        # 上传到uploda文件夹中
        # 解决文件名被覆盖
        #1. 文件名重命名  文件名.后缀 1.jpg   后缀不变 变文件名
        # 获取文件后缀
        filetext = os.path.splitext(file.filename)[1]
        newfile = uuid.uuid4().hex + filetext  # 前面新生成得文件名拼接后缀
        
        #2. 在upload下面建立文件夹专业存文件夹名为userid
        # 根据userid创建文件夹
        # 判断此用户得文件夹是否存在 存在就不用创建 直接写文件  不存在则创建
        path= './static/upload/'+str(userid)
        if not os.path.exists(path):  # 如果用户文件夹不存在
            os.mkdir(path)
        # 保存到  /static/upload/文件夹中
        file.save(os.path.join(path,newfile))
        # 更新到数据库 
        
        try:
            id = request.form.get('id')
            # 获取type
            type = int(request.form.get('type'))
            # print('----------------------------')
            # print(id,type)
            # print('----------------------------')
            if type==1:
                print('1231231231231231231')
                Course.query.filter_by(id=id).update({'pic':newfile})
            else:
                # 更新视频
                # 视频列表
                print('123456789765432123456754342')
                course = Course.query.filter_by(id=id).first()
                #获取视频列表转成列表
                if course.vedios:
                    clist = json.loads(course.vedios)
                    videoname = request.form['videoname']
                    
                    #把列表中视频文件替换
                    clist= [newfile if i==videoname else i for i in clist]
                    if len(clist) >0:
                        vedios=json.dumps(clist,ensure_ascii=False)
                    else:
                        vedios=''
                else:
                    vedios =json.dumps([newfile]) 
                    #更新数据库vedios
                    Course.query.filter_by(id=id).update({'vedios':vedios})
                
            db.session.commit()
        except:
            pass
            
        
        # 调用右拍云接口 将前端穿的图片传到右拍云服务器上
        # myup.upload1(newfile, userid) 
        return jsonify({"code":200,'filename':newfile})


@bp_cates.route('/deletepic/',methods=['DELETE'])
@sqlalchemy_context()
def deletepic():
    if request.method=='DELETE':
        name = request.args.get('name')
        userid = request.args.get('userid')
        if not name:
            return jsonify({"code":10041,'msg':'请传递删除的文件'})
        # 直接从服务器上删除
        id = request.args.get('id')
        print('-------------------------------------------')
        print(name)
        os.remove('./static/upload/'+str(userid)+'/'+name)
        #获取type
        type = int(request.args.get('type'))
        if type == 1:
            # 图片
            print('++++++++++++++++++++++++++++++++++++')
            Course.query.filter_by(id=id).update({'pic':''})
        else:
            # 视频列表
            print('lalalalallalalalalalallalalalallalalalalalalalallalalalalalal')
            course = Course.query.filter_by(id=id).first()
            if course.vedios:
                clist = json.loads(course.vedios)
                clist.remove(name)
                
                if len(clist)>0:
                    vedios = json.loads(clist,ensure_ascii=False)
                else:
                    vedios = ''
                Course.query.filter_by(id=id).update({'vedios':vedios})
        db.session.commit()
        return jsonify({'code':200,'msg':'删除成功'})

